package com.newland.mesdk.demo.fragment;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.newland.me.SupportMSDAlgorithm;
import com.newland.mesdk.demo.main.R;
import com.newland.mtype.DeviceRTException;
import com.newland.mtype.ModuleType;
import com.newland.mtype.common.ExCode;
import com.newland.mtype.common.MESeriesConst;
import com.newland.mtype.event.AbstractProcessDeviceEvent;
import com.newland.mtype.event.DeviceEvent;
import com.newland.mtype.event.DeviceEventListener;
import com.newland.mtype.module.common.cardreader.CommonCardType;
import com.newland.mtype.module.common.cardreader.OpenCardReaderEvent;
import com.newland.mtype.module.common.cardreader.OpenCardReaderResult;
import com.newland.mtype.module.common.emv.AIDConfig;
import com.newland.mtype.module.common.emv.CAPublicKey;
import com.newland.mtype.module.common.emv.EmvTransController;
import com.newland.mtype.module.common.emv.EmvTransInfo;
import com.newland.mtype.module.common.pin.AccountInputType;
import com.newland.mtype.module.common.pin.K21PininutEvent;
import com.newland.mtype.module.common.pin.KekUsingType;
import com.newland.mtype.module.common.pin.KeyManageType;
import com.newland.mtype.module.common.pin.PinConfirmType;
import com.newland.mtype.module.common.pin.PinInputEvent;
import com.newland.mtype.module.common.pin.PinInputResult;
import com.newland.mtype.module.common.pin.WorkingKey;
import com.newland.mtype.module.common.pin.WorkingKeyType;
import com.newland.mtype.module.common.rfcard.RFCardType;
import com.newland.mtype.module.common.swiper.SwipResult;
import com.newland.mtype.module.common.swiper.SwipResultType;
import com.newland.mtype.module.common.swiper.SwiperReadModel;
import com.newland.mtype.util.Dump;
import com.newland.mtype.util.ISOUtils;
import com.newland.mesdk.demo.activity.N900KeyBoardNumberActivity;
import com.newland.mesdk.demo.event.SimpleTransferListener;
import com.newland.mesdk.demo.interfaceimpl.CardReaderInterfaceImpl;
import com.newland.mesdk.demo.interfaceimpl.EmvInterfaceImpl;
import com.newland.mesdk.demo.interfaceimpl.K21EmvInterfaceImpl;
import com.newland.mesdk.demo.interfaceimpl.K21PininputInterfaceImpl;
import com.newland.mesdk.demo.interfaceimpl.PinInputInterfaceImpl;
import com.newland.mesdk.demo.interfaceimpl.QPBOCInterfaceImpl;
import com.newland.mesdk.demo.interfaceimpl.SwiperInterfaceImpl;
import com.newland.mesdk.demo.main.MainActivity;
import com.newland.mesdk.demo.main.MyApplication;
import com.newland.mesdk.demo.util.AppExCode;
import com.newland.mesdk.demo.util.Const;
import com.newland.mesdk.demo.util.SharedPreferencesUtil;
import com.newland.mesdk.demo.util.Const.MessageTag;

/**
 * Created by YJF 消费模块
 */
public class ConsumeFragment extends Fragment implements OnClickListener {
	private MainActivity mainActivity;
	private EmvTransController controller;
	private TextView tvOperationMessage;
	private StringBuffer stringBuffer;
	private int inputLen = 0;
	private String pininputString;
	private PinInputInterfaceImpl pinInputInterfaceImpl;
	private K21EmvInterfaceImpl k21EmvInterfaceImpl;
	private EmvInterfaceImpl emvInterfaceImpl;
	private BigDecimal amt;
	private int keyIndex = 87;
	private Dialog amt_dialog, pininput_dialog;
	private EditText edit_amt_input;
	private Button btn_sure, btn_cancel;
	private CharSequence temp;
	private String deviceType, connectType;
	private SimpleTransferListener simpleTransferListener;
	private byte[] rid = new byte[] { (byte) 0xA0, 0x00, 0x00, 0x03, 0x33 };
	protected static final String MAINKEY = "253C9D9D7C2FBBFA253C9D9D7C2FBBFA";// 主密钥预设输入值
	protected static final String WORKINGKEY_DATA_MAC = "DBFE96D0A5F09D24";// MAC秘钥预设输入值
	protected static final String WORKINGKEY_DATA_TRACK = "DBFE96D0A5F09D24DBFE96D0A5F09D24";// TRACK秘钥预设输入值
	protected static final String WORKINGKEY_DATA_PIN = "D2CEEE5C1D3AFBAF00374E0CC1526C86";// PIN秘钥预设输入值
	private Button btnLoadMk, btnLoadWk, btnLoadPk, btnLoadAID, btnConsume;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_consume, null);
		connectType = SharedPreferencesUtil.getStringParam(view.getContext(), Const.CONNECTTYPE);
		deviceType = SharedPreferencesUtil.getStringParam(view.getContext(), Const.DEVICETYPE);
		mainActivity = (MainActivity) getActivity();
		tvOperationMessage = (TextView) mainActivity.findViewById(R.id.test_info);
		simpleTransferListener = new SimpleTransferListener(mainActivity, deviceType);

		initConsumeView(view);
		return view;
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 2: // 键盘输入
				int len = (Integer) msg.obj;
				stringBuffer = new StringBuffer();
				for (int i = 0; i < len; i++) {
					stringBuffer.append(" * ");
				}
				tvOperationMessage.setText("正在密码输入:" + stringBuffer.toString());
				break;

			default:
				break;
			}
		}
	};

	public void initConsumeView(View view) {
		btnLoadMk = (Button) view.findViewById(R.id.btn_consume_load_mainkey);
		btnLoadMk.setOnClickListener(this);

		btnLoadWk = (Button) view.findViewById(R.id.btn_consume_load_wk);
		btnLoadWk.setOnClickListener(this);

		btnLoadPk = (Button) view.findViewById(R.id.btn_consume_load_pk);
		btnLoadPk.setOnClickListener(this);

		btnLoadAID = (Button) view.findViewById(R.id.btn_consume_load_aid);
		btnLoadAID.setOnClickListener(this);

		btnConsume = (Button) view.findViewById(R.id.btn_consume_consume);
		btnConsume.setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {
		if (mainActivity.isDeviceInit()) {
			mainActivity.connectDevice();
			pinInputInterfaceImpl = new PinInputInterfaceImpl();
			k21EmvInterfaceImpl = new K21EmvInterfaceImpl();
			emvInterfaceImpl = new EmvInterfaceImpl();
			switch (v.getId()) {
			case R.id.btn_consume_load_mainkey:
				if (mainActivity.processingisLocked()) {
					mainActivity.showMessage("请先完成或撤销当前操作...", MessageTag.ERROR);
				} else {
					new Thread(new Runnable() {

						@Override
						public void run() {
							mainActivity.processingLock();
							try {
								byte[] mainKey = pinInputInterfaceImpl.loadMainKey(KekUsingType.ENCRYPT_TMK,
										Const.MKIndexConst.DEFAULT_MK_INDEX, ISOUtils.hex2byte(MAINKEY),
										ISOUtils.hex2byte("82E13665"), 1);
								if (mainKey == null) {
									mainActivity.showMessage("主密钥装载失败!" + "\r\n", MessageTag.TIP);
								} else {
									mainActivity.showMessage("主密钥装载成功!" + "\r\n", MessageTag.TIP);
									mainActivity.showMessage("主密钥装载返回的数据：" + ISOUtils.hexString(mainKey) + "\r\n",
											MessageTag.DATA);
								}
								mainActivity.processingUnLock();
							} catch (Exception e) {
								mainActivity.showMessage("主密钥装载失败" + e.getMessage() + "\r\n", MessageTag.ERROR);
								mainActivity.processingUnLock();
							}
						}
					}).start();
				}

				break;
			case R.id.btn_consume_load_aid: {
				if (mainActivity.processingisLocked()) {
					mainActivity.showMessage("请先完成或撤销当前操作...", MessageTag.ERROR);
				} else {
					new Thread(new Runnable() {

						@Override
						public void run() {
							mainActivity.processingLock();
							try {
								mainActivity.showMessage("开始增加AID。。。" + "\r\n", MessageTag.TIP);
								AIDConfig aidConfig = new AIDConfig();
								aidConfig.setAid(ISOUtils.hex2byte("A000000333010102"));// 0x9f06
								aidConfig.setAppSelectIndicator(0);// 0xDF01
								aidConfig.setAppVersionNumberTerminal(new byte[] { 0x00, (byte) 0x20 });// 0x9f09
								aidConfig.setTacDefault(ISOUtils.hex2byte("FC78FCF8F0"));// 0xDF11
								aidConfig.setTacOnLine(ISOUtils.hex2byte("FC78FCF8F0"));// 0xDF12
								aidConfig.setTacDenial(ISOUtils.hex2byte("0010000000"));// 0xDF13
								aidConfig.setTerminalFloorLimit(new byte[] { 0x00, 0x00, 0x00, 0x05 });// 0x9f1b
								aidConfig.setThresholdValueForBiasedRandomSelection(new byte[] { 0x00, 0x00, 0x00,
										(byte) 0x28 });// 0xDF15
								aidConfig.setMaxTargetPercentageForBiasedRandomSelection(32);// 0xDF16
								aidConfig.setTargetPercentageForRandomSelection(14);// 0xDF17
								aidConfig.setDefaultDDOL(ISOUtils.hex2byte("9F3704"));// 0xDF14
								aidConfig.setOnLinePinCapability(1);// 0xDF18
								aidConfig.setEcTransLimit(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });// 0x9F7B
								aidConfig.setNciccOffLineFloorLimit(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });// 0xDF19
								aidConfig.setNciccTransLimit(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });// 0xDF20
								aidConfig.setNciccCVMLimit(new byte[] { 0x00, 0x00, 0x00, 0x00, (byte) 0x80, 0x00 });// 0xDF21
								aidConfig.setEcCapability(0);// 0xDF24
								aidConfig.setCoreConfigType(2);// 0xDF25
								boolean addAIDResult1 = false;
								if (connectType.equals(Const.ConnectTypeName.K21)) {
									k21EmvInterfaceImpl.initEmvModule(mainActivity);
									addAIDResult1 = k21EmvInterfaceImpl.addAID(aidConfig);
								} else {
									addAIDResult1 = emvInterfaceImpl.addAID(aidConfig);
								}
								mainActivity.showMessage("添加AID结果:" + addAIDResult1, MessageTag.DATA);

								AIDConfig aidConfig2 = new AIDConfig();
								aidConfig2.setAid(ISOUtils.hex2byte("A000000333010101"));// 0x9f06
								aidConfig2.setAppSelectIndicator(0);// 0xDF01
								aidConfig2.setAppVersionNumberTerminal(new byte[] { 0x00, (byte) 0x20 });// 0x9f09
								aidConfig2.setTacDefault(ISOUtils.hex2byte("FC78FCF8F0"));// 0xDF11
								aidConfig2.setTacOnLine(ISOUtils.hex2byte("FC78FCF8F0"));// 0xDF12
								aidConfig2.setTacDenial(ISOUtils.hex2byte("0010000000"));// 0xDF13
								aidConfig2.setTerminalFloorLimit(new byte[] { 0x00, 0x00, 0x00, 0x05 });// 0x9f1b
								aidConfig2.setThresholdValueForBiasedRandomSelection(new byte[] { 0x00, 0x00, 0x00,
										(byte) 0x28 });// 0xDF15
								aidConfig2.setMaxTargetPercentageForBiasedRandomSelection(32);// 0xDF16
								aidConfig2.setTargetPercentageForRandomSelection(14);// 0xDF17
								aidConfig2.setDefaultDDOL(ISOUtils.hex2byte("9F3704"));// 0xDF14
								aidConfig2.setOnLinePinCapability(1);// 0xDF18
								aidConfig2.setEcTransLimit(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });// 0x9F7B
								aidConfig2.setNciccOffLineFloorLimit(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });// 0xDF19
								aidConfig2.setNciccTransLimit(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });// 0xDF20
								aidConfig2.setNciccCVMLimit(new byte[] { 0x00, 0x00, 0x00, 0x00, (byte) 0x80, 0x00 });// 0xDF21
								aidConfig2.setEcCapability(0);// 0xDF24
								aidConfig2.setCoreConfigType(2);// 0xDF25
								boolean addAIDResult2 = false;
								if (connectType.equals(Const.ConnectTypeName.K21)) {
									k21EmvInterfaceImpl.initEmvModule(mainActivity);
									addAIDResult2 = k21EmvInterfaceImpl.addAID(aidConfig2);
								} else {
									addAIDResult2 = emvInterfaceImpl.addAID(aidConfig2);
								}
								mainActivity.showMessage("添加AID2结果:" + addAIDResult2, MessageTag.DATA);
								AIDConfig aidConfig3 = new AIDConfig();
								aidConfig3.setAid(ISOUtils.hex2byte("A000000333010103"));// 0x9f06
								aidConfig3.setAppSelectIndicator(0);// 0xDF01
								aidConfig3.setAppVersionNumberTerminal(new byte[] { 0x00, (byte) 0x20 });// 0x9f09
								aidConfig3.setTacDefault(ISOUtils.hex2byte("FC78FCF8F0"));// 0xDF11
								aidConfig3.setTacOnLine(ISOUtils.hex2byte("FC78FCF8F0"));// 0xDF12
								aidConfig3.setTacDenial(ISOUtils.hex2byte("0010000000"));// 0xDF13
								aidConfig3.setTerminalFloorLimit(new byte[] { 0x00, 0x00, 0x00, 0x05 });// 0x9f1b
								aidConfig3.setThresholdValueForBiasedRandomSelection(new byte[] { 0x00, 0x00, 0x00,
										(byte) 0x28 });// 0xDF15
								aidConfig3.setMaxTargetPercentageForBiasedRandomSelection(32);// 0xDF16
								aidConfig3.setTargetPercentageForRandomSelection(14);// 0xDF17
								aidConfig3.setDefaultDDOL(ISOUtils.hex2byte("9F3704"));// 0xDF14
								aidConfig3.setOnLinePinCapability(1);// 0xDF18
								aidConfig3.setEcTransLimit(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });// 0x9F7B
								aidConfig3.setNciccOffLineFloorLimit(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });// 0xDF19
								aidConfig3.setNciccTransLimit(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });// 0xDF20
								aidConfig3.setNciccCVMLimit(new byte[] { 0x00, 0x00, 0x00, 0x00, (byte) 0x80, 0x00 });// 0xDF21
								aidConfig3.setEcCapability(0);// 0xDF24
								aidConfig3.setCoreConfigType(2);// 0xDF25
								boolean addAIDResult3 = false;

								if (connectType.equals(Const.ConnectTypeName.K21)) {
									k21EmvInterfaceImpl.initEmvModule(mainActivity);
									addAIDResult3 = k21EmvInterfaceImpl.addAID(aidConfig3);
								} else {
									addAIDResult3 = emvInterfaceImpl.addAID(aidConfig3);
								}
								mainActivity.showMessage("添加AID3结果:" + addAIDResult3, MessageTag.DATA);
								AIDConfig aidConfig4 = new AIDConfig();
								aidConfig4.setAid(ISOUtils.hex2byte("A000000333010106"));// 0x9f06
								aidConfig4.setAppSelectIndicator(0);// 0xDF01
								aidConfig4.setAppVersionNumberTerminal(new byte[] { 0x00, (byte) 0x20 });// 0x9f09
								aidConfig4.setTacDefault(ISOUtils.hex2byte("FC78FCF8F0"));// 0xDF11
								aidConfig4.setTacOnLine(ISOUtils.hex2byte("FC78FCF8F0"));// 0xDF12
								aidConfig4.setTacDenial(ISOUtils.hex2byte("0010000000"));// 0xDF13
								aidConfig4.setTerminalFloorLimit(new byte[] { 0x00, 0x00, 0x00, 0x05 });// 0x9f1b
								aidConfig4.setThresholdValueForBiasedRandomSelection(new byte[] { 0x00, 0x00, 0x00,
										(byte) 0x28 });// 0xDF15
								aidConfig4.setMaxTargetPercentageForBiasedRandomSelection(32);// 0xDF16
								aidConfig4.setTargetPercentageForRandomSelection(14);// 0xDF17
								aidConfig4.setDefaultDDOL(ISOUtils.hex2byte("9F3704"));// 0xDF14
								aidConfig4.setOnLinePinCapability(1);// 0xDF18
								aidConfig4.setEcTransLimit(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });// 0x9F7B
								aidConfig4.setNciccOffLineFloorLimit(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });// 0xDF19
								aidConfig4.setNciccTransLimit(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });// 0xDF20
								aidConfig4.setNciccCVMLimit(new byte[] { 0x00, 0x00, 0x00, 0x00, (byte) 0x80, 0x00 });// 0xDF21
								aidConfig4.setEcCapability(0);// 0xDF24
								aidConfig4.setCoreConfigType(2);// 0xDF25

								boolean addAIDResult4 = false;
								if (connectType.equals(Const.ConnectTypeName.K21)) {
									k21EmvInterfaceImpl.initEmvModule(mainActivity);
									addAIDResult4 = k21EmvInterfaceImpl.addAID(aidConfig4);
								} else {
									addAIDResult4 = emvInterfaceImpl.addAID(aidConfig4);
								}

								mainActivity.showMessage("添加AID4结果:" + addAIDResult4, MessageTag.DATA);
								mainActivity.processingUnLock();
							} catch (Exception e) {
								mainActivity.showMessage("增加AID：异常！" + e + "\r\n", MessageTag.ERROR);
								mainActivity.processingUnLock();
							}
						}
					}).start();
				}

				break;
			}
			case R.id.btn_consume_load_wk: {
				if (mainActivity.processingisLocked()) {
					mainActivity.showMessage("请先完成或撤销当前操作...", MessageTag.ERROR);
				} else {
					new Thread(new Runnable() {

						@Override
						public void run() {
							mainActivity.processingLock();
							showLoadWorkingKeyDiaolg(mainActivity);
						}
					}).start();

				}

				break;
			}
			case R.id.btn_consume_load_pk: {
				if (mainActivity.processingisLocked()) {
					mainActivity.showMessage("请先完成或撤销当前操作...", MessageTag.ERROR);
				} else {
					new Thread(new Runnable() {

						@Override
						public void run() {
							try {
								mainActivity.processingLock();
								mainActivity.showMessage("开始添加公钥...", MessageTag.TIP);
								int P9f22_1 = 1;
								keyIndex = P9f22_1;
								byte[] df02_2 = ISOUtils
										.hex2byte("BBE9066D2517511D239C7BFA77884144AE20C7372F515147E8CE6537C54C0A6A4D45F8CA4D290870CDA59F1344EF71D17D3F35D92F3F06778D0D511EC2A7DC4FFEADF4FB1253CE37A7B2B5A3741227BEF72524DA7A2B7B1CB426BEE27BC513B0CB11AB99BC1BC61DF5AC6CC4D831D0848788CD74F6D543AD37C5A2B4C5D5A93B");
								byte[] df04_2 = ISOUtils.hex2byte("000003");
								byte[] df03_2 = ISOUtils.hex2byte("E881E390675D44C2DD81234DCE29C3F5AB2297A0");
								CAPublicKey caKey2 = new CAPublicKey(P9f22_1, 1, 1, df02_2, df04_2, df03_2, "20091231");
								boolean addCAPK2 = false;
								if (connectType.equals(Const.ConnectTypeName.K21)) {
									k21EmvInterfaceImpl.initEmvModule(mainActivity);
									addCAPK2 = k21EmvInterfaceImpl.addCAPublicKey(rid, caKey2);
								} else {
									addCAPK2 = emvInterfaceImpl.addCAPublicKey(rid, caKey2);
								}
								mainActivity.showMessage("添加公钥1结果:" + addCAPK2, MessageTag.DATA);
								mainActivity.showMessage("索引号为:" + P9f22_1, MessageTag.DATA);

								int P9f22_2 = 2;
								keyIndex = P9f22_2;
								byte[] df02 = ISOUtils
										.hex2byte("A3767ABD1B6AA69D7F3FBF28C092DE9ED1E658BA5F0909AF7A1CCD907373B7210FDEB16287BA8E78E1529F443976FD27F991EC67D95E5F4E96B127CAB2396A94D6E45CDA44CA4C4867570D6B07542F8D4BF9FF97975DB9891515E66F525D2B3CBEB6D662BFB6C3F338E93B02142BFC44173A3764C56AADD202075B26DC2F9F7D7AE74BD7D00FD05EE430032663D27A57");
								byte[] df04 = ISOUtils.hex2byte("000003");
								byte[] df03 = ISOUtils.hex2byte("03BB335A8549A03B87AB089D006F60852E4B8060");
								CAPublicKey caKey1 = new CAPublicKey(P9f22_2, 1, 1, df02, df04, df03, "20141231");
								boolean addCAPK1 = false;
								if (connectType.equals(Const.ConnectTypeName.K21)) {
									k21EmvInterfaceImpl.initEmvModule(mainActivity);
									addCAPK1 = k21EmvInterfaceImpl.addCAPublicKey(rid, caKey1);
								} else {
									addCAPK1 = emvInterfaceImpl.addCAPublicKey(rid, caKey1);
								}
								mainActivity.showMessage("添加公钥2结果:" + addCAPK1, MessageTag.DATA);
								mainActivity.showMessage("索引号为:" + P9f22_2, MessageTag.DATA);

								int P9f22_3 = 3;
								keyIndex = P9f22_3;
								byte[] df02_3 = ISOUtils
										.hex2byte("B0627DEE87864F9C18C13B9A1F025448BF13C58380C91F4CEBA9F9BCB214FF8414E9B59D6ABA10F941C7331768F47B2127907D857FA39AAF8CE02045DD01619D689EE731C551159BE7EB2D51A372FF56B556E5CB2FDE36E23073A44CA215D6C26CA68847B388E39520E0026E62294B557D6470440CA0AEFC9438C923AEC9B2098D6D3A1AF5E8B1DE36F4B53040109D89B77CAFAF70C26C601ABDF59EEC0FDC8A99089140CD2E817E335175B03B7AA33D");
								byte[] df04_3 = ISOUtils.hex2byte("000003");
								byte[] df03_3 = ISOUtils.hex2byte("87F0CD7C0E86F38F89A66F8C47071A8B88586F26");
								CAPublicKey caKey3 = new CAPublicKey(P9f22_3, 1, 1, df02_3, df04_3, df03_3, "20171231");
								boolean addCAPK3 = false;
								if (connectType.equals(Const.ConnectTypeName.K21)) {
									k21EmvInterfaceImpl.initEmvModule(mainActivity);
									addCAPK3 = k21EmvInterfaceImpl.addCAPublicKey(rid, caKey3);
								} else {
									addCAPK3 = emvInterfaceImpl.addCAPublicKey(rid, caKey3);
								}

								mainActivity.showMessage("添加公钥3结果:" + addCAPK3, MessageTag.DATA);
								mainActivity.showMessage("索引号为:" + P9f22_3, MessageTag.DATA);

								int P9f22_4 = 4;
								keyIndex = P9f22_4;
								byte[] df02_4 = ISOUtils
										.hex2byte("BC853E6B5365E89E7EE9317C94B02D0ABB0DBD91C05A224A2554AA29ED9FCB9D86EB9CCBB322A57811F86188AAC7351C72BD9EF196C5A01ACEF7A4EB0D2AD63D9E6AC2E7836547CB1595C68BCBAFD0F6728760F3A7CA7B97301B7E0220184EFC4F653008D93CE098C0D93B45201096D1ADFF4CF1F9FC02AF759DA27CD6DFD6D789B099F16F378B6100334E63F3D35F3251A5EC78693731F5233519CDB380F5AB8C0F02728E91D469ABD0EAE0D93B1CC66CE127B29C7D77441A49D09FCA5D6D9762FC74C31BB506C8BAE3C79AD6C2578775B95956B5370D1D0519E37906B384736233251E8F09AD79DFBE2C6ABFADAC8E4D8624318C27DAF1");
								byte[] df04_4 = ISOUtils.hex2byte("000003");
								byte[] df03_4 = ISOUtils.hex2byte("F527081CF371DD7E1FD4FA414A665036E0F5E6E5");
								CAPublicKey caKey4 = new CAPublicKey(P9f22_4, 1, 1, df02_4, df04_4, df03_4, "20171231");

								boolean addCAPK4 = false;
								if (connectType.equals(Const.ConnectTypeName.K21)) {
									k21EmvInterfaceImpl.initEmvModule(mainActivity);
									addCAPK4 = k21EmvInterfaceImpl.addCAPublicKey(rid, caKey4);
								} else {
									addCAPK4 = emvInterfaceImpl.addCAPublicKey(rid, caKey4);
								}

								mainActivity.showMessage("添加公钥4结果:" + addCAPK4, MessageTag.DATA);
								mainActivity.showMessage("索引号为:" + P9f22_4, MessageTag.DATA);
								mainActivity.processingUnLock();
							} catch (Exception e) {
								mainActivity.showMessage("添加公钥结果:" + "异常" + e.getMessage(), MessageTag.ERROR);
								mainActivity.processingUnLock();
							}
						}
					}).start();
				}

				break;
			}
			case R.id.btn_consume_consume: {
				if (mainActivity.processingisLocked()) {
					mainActivity.showMessage("请先完成或撤销当前操作...", MessageTag.ERROR);
				} else {
					new Thread(new Runnable() {

						@Override
						public void run() {
							mainActivity.processingLock();
							showInputAmoutDialog();

						}
					}).start();
				}

				break;
			}

			default:
				break;
			}
		} else {
			mainActivity.showMessage("设备未初始化，请先初始化！" + "\r\n", MessageTag.NORMAL);
		}
	}

	// 装载工作秘钥对话框
	public void showLoadWorkingKeyDiaolg(final Activity activity) {
		mainActivity.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				try {
					final boolean[] arrayWorkingKeySelected = new boolean[] { false, false, false };
					final String[] arrayWorkingKey = new String[] { "PIN密钥", "磁道密钥", "MAC密钥" };
					final AlertDialog.Builder builder = new android.app.AlertDialog.Builder(activity);
					builder.setTitle("请选择需装载工作密钥类型:");
					builder.setMultiChoiceItems(arrayWorkingKey, arrayWorkingKeySelected,
							new DialogInterface.OnMultiChoiceClickListener() {
								@Override
								public void onClick(DialogInterface arg0, int arg1, boolean arg2) {
									arrayWorkingKeySelected[arg1] = arg2;
								}
							});

					builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							try {
								mainActivity.showMessage("正在装载工作密钥..." + "\r\n", MessageTag.TIP);
								int mkIndex = Const.MKIndexConst.DEFAULT_MK_INDEX;
								if (arrayWorkingKeySelected[0] == true) {
									byte[] wk_pin = pinInputInterfaceImpl.loadWorkingKey(WorkingKeyType.PININPUT,
											mkIndex, Const.PinWKIndexConst.DEFAULT_PIN_WK_INDEX,
											ISOUtils.hex2byte(WORKINGKEY_DATA_PIN), ISOUtils.hex2byte("58A2BBF9"));
									if (wk_pin != null) {
										mainActivity.showMessage("pin工作密钥装载成功!" + "\r\n", MessageTag.NORMAL);
										mainActivity.processingUnLock();
									} else {
										mainActivity.showMessage("pin工作密钥装载失败!" + "\r\n", MessageTag.NORMAL);
										mainActivity.processingUnLock();
									}
								}
								if (arrayWorkingKeySelected[1] == true) {
									byte[] wk_encrypt = pinInputInterfaceImpl.loadWorkingKey(
											WorkingKeyType.DATAENCRYPT, mkIndex,
											Const.DataEncryptWKIndexConst.DEFAULT_TRACK_WK_INDEX,
											ISOUtils.hex2byte(WORKINGKEY_DATA_TRACK), ISOUtils.hex2byte("5B4C8BED"));
									if (wk_encrypt != null) {
										mainActivity.showMessage("磁道工作密钥装载成功!" + "\r\n", MessageTag.NORMAL);
										mainActivity.processingUnLock();
									} else {
										mainActivity.showMessage("磁道工作密钥装载失败!" + "\r\n", MessageTag.NORMAL);
										mainActivity.processingUnLock();
									}
								}
								if (arrayWorkingKeySelected[2] == true) {
									byte[] wk_mac = pinInputInterfaceImpl.loadWorkingKey(WorkingKeyType.MAC, mkIndex,
											Const.MacWKIndexConst.DEFAULT_MAC_WK_INDEX,
											ISOUtils.hex2byte(WORKINGKEY_DATA_MAC), ISOUtils.hex2byte("5B4C8BED"));
									if (wk_mac != null) {
										mainActivity.showMessage("mac工作密钥装载成功!" + "\r\n", MessageTag.NORMAL);
										mainActivity.processingUnLock();
									} else {
										mainActivity.showMessage("mac工作密钥装载失败!" + "\r\n", MessageTag.ERROR);
										mainActivity.processingUnLock();
									}
								}

							} catch (Exception e) {
								mainActivity.showMessage(e.getMessage() + "\r\n", MessageTag.ERROR);
								mainActivity.processingUnLock();
							}
						}

					});
					builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							mainActivity.processingUnLock();
						}
					});
					Dialog workingkey_dialog = builder.create();
					workingkey_dialog.setCancelable(false);
					workingkey_dialog.setCanceledOnTouchOutside(false);
					workingkey_dialog.show();
				} catch (Exception ex) {
					mainActivity.showMessage("工作密钥装载失败!" + ex.getMessage() + "\r\n", MessageTag.ERROR);
				}
			}
		});
	}

	// 输入消费金额对话框
	public void showInputAmoutDialog() {
		mainActivity.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				final AlertDialog.Builder builder = new android.app.AlertDialog.Builder(mainActivity);
				LayoutInflater inflater = LayoutInflater.from(mainActivity);
				final View view = inflater.inflate(R.layout.dialog_amtinput, null);
				builder.setTitle("请输入交易金额（最高12位）:");
				edit_amt_input = (EditText) view.findViewById(R.id.edit_amt_input);
				btn_sure = (Button) view.findViewById(R.id.btn_sure);
				btn_cancel = (Button) view.findViewById(R.id.btn_cancel);
				edit_amt_input.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
				builder.setView(view);
				edit_amt_input.addTextChangedListener(new TextWatcher() {
					@Override
					public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
						temp = arg0;
					}

					@Override
					public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
					}

					@Override
					public void afterTextChanged(Editable arg0) {
						if (temp.length() > 12) {
							btn_sure.setEnabled(false);
						} else {
							btn_sure.setEnabled(true);
						}

					}
				});

				btn_sure.setOnClickListener(new android.view.View.OnClickListener() {
					@Override
					public void onClick(View arg0) {
						Editable editable = edit_amt_input.getText();
						try {
							DecimalFormat df = new DecimalFormat("#.00");
							amt = new BigDecimal(editable.toString());
							((MyApplication) mainActivity.getApplication()).setAmt(amt);
							mainActivity.showMessage("交易金额为:" + df.format(amt) + "\r\n", MessageTag.NORMAL);
							amt_dialog.dismiss();
							new Thread(new Runnable() {

								@Override
								public void run() {
									try {
										mainActivity.showMessage("请刷卡或者插入IC卡..." + "\r\n", MessageTag.TIP);
										CardReaderInterfaceImpl cardReaderInterfaceImpl = new CardReaderInterfaceImpl();
										EventHolder<OpenCardReaderEvent> listener = new EventHolder<OpenCardReaderEvent>();
										cardReaderInterfaceImpl
												.openCardReader("请刷卡或者插入IC卡", new ModuleType[] {
														ModuleType.COMMON_SWIPER, ModuleType.COMMON_ICCARDREADER,
														ModuleType.COMMON_RFCARDREADER }, new RFCardType[] {
														RFCardType.ACARD, RFCardType.BCARD, RFCardType.M1CARD }, true,
														true, 60, TimeUnit.SECONDS,listener);
										try {
											listener.startWait();
										} catch (InterruptedException e) {
											cardReaderInterfaceImpl.cancelCardRead();
											mainActivity.showMessage("用户撤销刷卡操作！", MessageTag.TIP);

										} 
										OpenCardReaderEvent event = listener.event;
										event = preEvent(event, AppExCode.GET_TRACKTEXT_FAILED);
										if (event == null) {
											mainActivity.showMessage("用户撤销刷卡操作！", MessageTag.TIP);
											return;
										}
										OpenCardReaderResult cardResult = event.getOpenCardReaderResult();
										CommonCardType[] openedModuleTypes = cardResult.getResponseCardTypes();
										mainActivity.showMessage("读卡器开启成功" + "\r\n", MessageTag.TIP);
										if (cardResult == null || openedModuleTypes.length <= 0) {
											mainActivity.showMessage(
													"start cardreader,but return is none!may user canceled?",
													MessageTag.ERROR);
											mainActivity.processingUnLock();
										}
										if (openedModuleTypes.length > 1) {
											mainActivity.showMessage(
													"should return only one type of cardread action!but is "
															+ openedModuleTypes.length, MessageTag.ERROR);
											mainActivity.processingUnLock();
											throw new DeviceRTException(AppExCode.GET_TRACKTEXT_FAILED,
													"should return only one type of cardread action!but is "
															+ openedModuleTypes.length);

										}
										switch (openedModuleTypes[0]) {
										case MSCARD:
											mainActivity.showMessage("当前的卡为:磁条卡" + "\r\n", MessageTag.TIP);
											boolean isCorrent = cardResult.isMSDDataCorrectly();
											if (!isCorrent) {
												throw new DeviceRTException(AppExCode.GET_TRACKTEXT_FAILED,
														"swip failed!");
											}
											SwiperInterfaceImpl swiperInterfaceImpl = new SwiperInterfaceImpl();
											SwipResult swipRslt = swiperInterfaceImpl
													.readEncryptResult(
															new SwiperReadModel[] { SwiperReadModel.READ_SECOND_TRACK },
															new WorkingKey(
																	Const.DataEncryptWKIndexConst.DEFAULT_TRACK_WK_INDEX),
															SupportMSDAlgorithm
																	.getMSDAlgorithm(MESeriesConst.TrackEncryptAlgorithm.BY_UNIONPAY_MODEL));
											;
											if (null != swipRslt && swipRslt.getRsltType() == SwipResultType.SUCCESS) {
												((MyApplication) (mainActivity).getApplication())
														.setSwipResult(swipRslt);
												mainActivity.showMessage("刷卡成功" + "\r\n", MessageTag.TIP);
												mainActivity.showMessage("请输入密码" + "\r\n", MessageTag.TIP);
												doPinInput(swipRslt);
											} else {
												mainActivity.showMessage("刷卡结果空了,请重刷" + "\r\n", MessageTag.TIP);
											}
											mainActivity.processingUnLock();
											break;
										case ICCARD:
											mainActivity.showMessage("当前的卡为IC卡" + "\r\n", MessageTag.TIP);
											try {
												((MyApplication) (mainActivity).getApplication())
														.setOpen_card_reader_flag(0);
												if (connectType.equals(Const.ConnectTypeName.K21)) {
													k21EmvInterfaceImpl.initEmvModule(mainActivity);
													controller = k21EmvInterfaceImpl
															.getEmvTransController(simpleTransferListener);
												} else {
													controller = emvInterfaceImpl
															.getEmvTransController(simpleTransferListener);
												}

												if (controller != null) {
													mainActivity.showMessage("IC Card start emv..." + "\r\n",
															MessageTag.TIP);

													controller.startEmv(amt, new BigDecimal("0"), true );
												}
											} catch (Exception e) {
												mainActivity.showMessage("IC Card emv 流程异常..." + e + "\r\n",
														MessageTag.ERROR);
												mainActivity.processingUnLock();
											}

											break;
										case RFCARD:
											if (connectType.equals(Const.ConnectTypeName.K21)) {
												k21EmvInterfaceImpl.initEmvModule(mainActivity);
												controller = k21EmvInterfaceImpl.getEmvTransController(simpleTransferListener);
												if (controller != null) {
													mainActivity.showMessage("RF Card start emv..." + "\r\n", MessageTag.TIP);
													controller.startEmv(0x00, 0x0B,amt, new BigDecimal("0"), false);
												}
											} else {
												mainActivity.showMessage("当前的卡为非接卡" + "\r\n", MessageTag.TIP);
												QPBOCInterfaceImpl qpbocInterfaceImpl = new QPBOCInterfaceImpl();
												EmvTransInfo emvTransInfo = qpbocInterfaceImpl.startQPBOC(amt, 60,
														TimeUnit.SECONDS);
												simpleTransferListener.onQpbocFinished(emvTransInfo);
											}

											break;
										default:
											throw new DeviceRTException(AppExCode.GET_TRACKTEXT_FAILED,
													"not support cardreader module:" + openedModuleTypes[0]);
										}

									} catch (Exception e) {
										e.printStackTrace();
										mainActivity.showMessage("读卡器开启异常" + "\r\n", MessageTag.ERROR);
										mainActivity.showMessage(e.getMessage() + "\r\n", MessageTag.ERROR);
										mainActivity.processingUnLock();
									}
								}
							}).start();

						} catch (Exception e) {
							mainActivity.showMessage("输入金额异常：" + e, MessageTag.ERROR);
							mainActivity.processingUnLock();
						}
					}
				});

				btn_cancel.setOnClickListener(new android.view.View.OnClickListener() {
					@Override
					public void onClick(View arg0) {
						mainActivity.showMessage("交易取消" + "\r\n", MessageTag.TIP);
						amt_dialog.dismiss();
						mainActivity.processingUnLock();
					}
				});
				amt_dialog = builder.create();
				amt_dialog.show();
				amt_dialog.setCanceledOnTouchOutside(false);
			}
		});
	}

	// 密码输入
	private void doPinInput(final SwipResult swipResult) {
		BigDecimal consumAmt = amt;
		DecimalFormat df = new DecimalFormat("#.00");
		String msg = "消费金额为:" + df.format(consumAmt) + "\n请输入交易密码:";
		PinInputEvent event = null;
		if (Const.DeviceName.ME30.equals(deviceType) || Const.DeviceName.ME31.equals(deviceType)) {
			String acctHash = swipResult.getAccount().getAcctHashId();

			event = pinInputInterfaceImpl.startStandardPinInput(new WorkingKey(
					Const.PinWKIndexConst.DEFAULT_PIN_WK_INDEX), KeyManageType.MKSK, AccountInputType.USE_ACCT_HASH,
					acctHash, 6, new byte[] { 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'F' }, true, msg, 60,
					TimeUnit.SECONDS);
			if (event == null) {
				mainActivity.showMessage("密码输入撤销" + "\r\n", MessageTag.TIP);
				mainActivity.processingUnLock();
				return;
			} else if (event.isSuccess()) {
				mainActivity.showMessage("密码输入完成" + "\r\n", MessageTag.TIP);
				mainActivity.showMessage("ksn:" + Dump.getHexDump(event.getKsn()) + "\r\n", MessageTag.DATA);
				mainActivity.showMessage("密码:" + Dump.getHexDump(event.getEncrypPin()) + "\r\n", MessageTag.DATA);
				mainActivity.showMessage("刷卡消费完成" + "\r\n", MessageTag.TIP);
				mainActivity.processingUnLock();
			}
		} else if (Const.DeviceName.IM81.equals(deviceType)) {// IM81连接方式
			String acctHash = swipResult.getAccount().getAcctHashId();
			K21PininputInterfaceImpl k21PinputInterfaceImpl = new K21PininputInterfaceImpl();
			k21PinputInterfaceImpl.startK21StandPininput("IM81开始输入密码", new WorkingKey(
					Const.PinWKIndexConst.DEFAULT_PIN_WK_INDEX), KeyManageType.MKSK, AccountInputType.USE_ACCT_HASH,
					acctHash, 6, null, new byte[] { 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'F' },
					PinConfirmType.ENABLE_ENTER_COMMANG, 6000, TimeUnit.SECONDS, null, null,
					new DeviceEventListener<K21PininutEvent>() {
						@Override
						public void onEvent(K21PininutEvent event, Handler handler) {

							if (event == null) {
								inputLen = 0;
								mainActivity.showMessage("密码输入撤销" + "\r\n", MessageTag.TIP);
								mainActivity.processingUnLock();
							} else if (event.isSuccess()) {
								inputLen = 0;
								mainActivity.showMessage("密码输入完成" + "\r\n", MessageTag.TIP);
								mainActivity.showMessage("ksn:" + Dump.getHexDump(event.getKsn()) + "\r\n",
										MessageTag.DATA);
								mainActivity.showMessage("密码:" + Dump.getHexDump(event.getEncrypPin()) + "\r\n",
										MessageTag.DATA);
								mainActivity.showMessage("刷卡消费完成" + "\r\n", MessageTag.TIP);
								mainActivity.processingUnLock();
							} else if (event.isProcessing()) {
								PinInputEvent.NotifyStep notifyStep = event.getNotifyStep();
								if (notifyStep == PinInputEvent.NotifyStep.ENTER) {
									inputLen = inputLen + 1;
								} else if (notifyStep == PinInputEvent.NotifyStep.BACKSPACE) {
									inputLen = (inputLen <= 0 ? 0 : inputLen - 1);
									mainActivity.showMessage("按了退格键:" + inputLen, MessageTag.TIP);
								}
								Message msg = mHandler.obtainMessage(2);
								msg.obj = inputLen;
								msg.sendToTarget();
							} else if (event.isUserCanceled()) {
								mainActivity.showMessage("取消密码输入" + "\r\n", MessageTag.TIP);
								inputLen = 0;
								mainActivity.processingUnLock();
							} else {
								mainActivity.showMessage("密码输入错误" + "\r\n", MessageTag.TIP);
								inputLen = 0;
								mainActivity.processingUnLock();
							}
						}

						@Override
						public Handler getUIHandler() {
							return null;
						}
					});
		} else if (Const.DeviceName.N900.equals(deviceType)) {
			try {
				mainActivity.processingLock();
				Message pinMsg = MainActivity.getPinHandler().obtainMessage(1);
				pinMsg.sendToTarget();
			} catch (Exception e) {
				mainActivity.showMessage("N900密码输入异常：" + e + "\r\n", MessageTag.ERROR);
				mainActivity.processingUnLock();
			}
		} else if (deviceType.equals(Const.DeviceName.AUDIO)) {
			mainActivity.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					final AlertDialog.Builder builder = new AlertDialog.Builder(mainActivity);
					LayoutInflater inflater = LayoutInflater.from(mainActivity);
					final View view = inflater.inflate(R.layout.dialog_pininput, null);
					final EditText pininput_value = (EditText) view.findViewById(R.id.password);
					builder.setView(view);
					builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							pininputString = pininput_value.getText().toString();
							if (pininputString == null) {
								tvOperationMessage.append("输入密码为空!" + "\r\n");
								mainActivity.processingUnLock();
								return;
							}
							try {
								PinInputResult result = null;
								result = pinInputInterfaceImpl.encryptPIN(new WorkingKey(
										Const.PinWKIndexConst.DEFAULT_PIN_WK_INDEX), KeyManageType.MKSK,
										AccountInputType.USE_ACCOUNT, swipResult.getAccount().getAcctNo(),
										pininputString.getBytes());
								if (result != null) {
									tvOperationMessage.append("密码输入完成" + "\r\n");
									tvOperationMessage.append("ksn:" + Dump.getHexDump(result.getKSN()) + "\r\n");
									tvOperationMessage.append("密码:" + Dump.getHexDump(result.getPinblock()) + "\r\n");
									tvOperationMessage.append("交易完成" + "\r\n");
									mainActivity.processingUnLock();
								} else {
									tvOperationMessage.append("输入密码为空!" + "\r\n");
									mainActivity.processingUnLock();
								}
							} catch (Exception e) {
								tvOperationMessage.append("密码输入失败!" + e + "\r\n");
								mainActivity.processingUnLock();
							}
						}
					});
					builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							tvOperationMessage.append("输入密码为空!" + "\r\n");
							pininput_dialog.dismiss();
							mainActivity.processingUnLock();
						}
					});
					pininput_dialog = builder.create();
					pininput_dialog.setTitle("密码输入");
					pininput_dialog.show();
					pininput_dialog.setCancelable(false);
					pininput_dialog.setCanceledOnTouchOutside(false);
				}
			});
		}
	}
	/**
	 * 事件线程阻塞控制监听
	 * <p>
	 * 
	 * @author lance
	 * 
	 * @param <T>
	 */
	private class EventHolder<T extends DeviceEvent> implements DeviceEventListener<T> {

		private T event;

		private final Object syncObj = new Object();

		private boolean isClosed = false;

		public void onEvent(T event, Handler handler) {
			this.event = event;
			if(event instanceof PinInputEvent&&((PinInputEvent) event).isProcessing()){
				return;
			}
			synchronized (syncObj) {
				isClosed = true;
				syncObj.notify();
			}
		}

		public Handler getUIHandler() {
			return null;
		}

		void startWait() throws InterruptedException {
			synchronized (syncObj) {
				if (!isClosed)
					syncObj.wait();
			}
		}

	}
	private <T extends AbstractProcessDeviceEvent> T preEvent(T event, int defaultExCode) {
		if (!event.isSuccess()) {
			if (event.isUserCanceled()) {
				return null;
			}
			if (event.getException() != null) {
				if (event.getException() instanceof RuntimeException) {// 运行时异常直接抛出
					throw (RuntimeException) event.getException();
				}
				throw new DeviceRTException(AppExCode.GET_TRACKTEXT_FAILED, "open card reader meet error!", event.getException());
			}
			throw new DeviceRTException(ExCode.UNKNOWN, "unknown exception!defaultExCode:" + defaultExCode);
		}
		return event;
	}
}
